package yogaService

import (
	"duoke/model"
	"duoke/model/yogaModel"
	"duoke/service/common"
	utils "duoke/utils/common"
	"duoke/utils/orm"
	"errors"
	"github.com/gin-gonic/gin"
	"strings"
	"time"
)

var Venue = new(venueService)

type venueService struct{}

func (s *venueService) List(c *gin.Context, req *model.ReqList) (*[]yogaModel.ReqVenue, int64, error) {
	where := ""
	var m []yogaModel.ReqVenue
	count, err := common.Tales.List(c, req, "weight desc").
		Table("yoga_venue").Where(where).FindAndCount(&m)
	for i := range m {
		// 先判断时间 今天是否在营业时间 再判断日期是否再营业日期
		if s.IsBusiness(m[i].BusinessDate, m[i].StartTime, m[i].EndTime) {
			m[i].IsBusiness = 1
		} else {
			m[i].IsBusiness = 2
		}
	}
	return &m, count, err
}

// IsBusiness 判断是否营业
func (s *venueService) IsBusiness(req string, start, end string) bool {
	// 将字段周一至周日 用至字分割开
	inRange, err := utils.Common.IsTimeInRange(start, end)
	if err != nil {
		return false
	}
	week := strings.Split(req, "至")
	day := map[string]time.Weekday{
		"周一": time.Monday,
		"周二": time.Tuesday,
		"周三": time.Wednesday,
		"周四": time.Thursday,
		"周五": time.Friday,
		"周六": time.Saturday,
		"周日": time.Sunday,
	}
	if len(week) < 2 {
		return false
	}
	weekday := time.Now().Weekday()
	return day[week[0]] <= weekday && weekday <= day[week[1]] && inRange
}

func (s *venueService) Save(c *gin.Context, req *yogaModel.ReqVenue) error {
	if req.Id > 0 {
		rows, err := orm.Db.Where("id=?", req.Id).Table("yoga_venue").Update(req)
		if rows == 0 || err != nil {
			return errors.New("保存失败")
		}
		// 修改成功后  修改课程表 将修改的name字段同步
		go func() {
			orm.Db.Where("venue_id=?", req.Id).
				Table("yoga_course").Update(map[string]string{"venue_name": req.Name})
			orm.Db.Where("venue_id=?", req.Id).
				Table("yoga_group_class").Update(map[string]string{"venue_name": req.Name})
		}()
	} else {
		rows, err := orm.Db.Insert(req)
		if rows == 0 || err != nil {
			return errors.New("保存失败")
		}
	}
	return nil
}
